use ratatui::{buffer::Buffer, layout::{self, Constraint, Direction, Rect}, widgets::{Block, Borders, Padding, Widget}};

use super::{Folder, Preview};
use crate::{core::manager::{Mode, ALL_RATIO, CURRENT_RATIO, PARENT_RATIO, PREVIEW_RATIO}, ui::Ctx};

pub struct Layout<'a> {
    cx: &'a Ctx,
}

impl<'a> Layout<'a> {
    pub fn new(cx: &'a Ctx) -> Self { Self { cx } }
}

impl<'a> Widget for Layout<'a> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        let manager = &self.cx.manager;
        
        // 将区域划分成三栏
        let chunks = layout::Layout::default()
            .direction(Direction::Horizontal)
            .constraints(
                [
                    Constraint::Ratio(PARENT_RATIO, ALL_RATIO),  // 父目录区域比例
                    Constraint::Ratio(CURRENT_RATIO, ALL_RATIO), // 当前目录区域比例
                    Constraint::Ratio(PREVIEW_RATIO, ALL_RATIO), // 预览区域比例
                ]
                    .as_ref(),
            )
            .split(area);

        // Parent
        let block = Block::default()
            .borders(Borders::RIGHT) // 右侧边框
            .padding(Padding::new(1, 0, 0, 0));  // 左侧内边距
        if let Some(ref parent) = manager.parent() {
            Folder::new(self.cx, parent).render(block.inner(chunks[0]), buf);
        }
        block.render(chunks[0], buf);

        // Current   渲染当前目录区域
        Folder::new(self.cx, manager.current())
            .with_selection(matches!(manager.active().mode(), Mode::Select(_)))  // 选择模式
            .render(chunks[1], buf);

        // Preview  渲染预览区域  
        let block = Block::default()
            .borders(Borders::LEFT) // 左侧边框
            .padding(Padding::new(0, 1, 0, 0));  // 右侧内边距
        Preview::new(self.cx).render(block.inner(chunks[2]), buf);
        block.render(chunks[2], buf);
    }
}
